﻿// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.DependencyInjection;

Console.WriteLine("Hello, World!");

//void Test(ref int b)
//{

//}

//void Test2(int b)
//{

//}

//int a = 1;

//Test(ref a);
//Test2(a);

//void Test(ref Demo b)
//{ }
//void Test2(Demo b)
//{ }

//Demo a = new Demo();
////Test(ref a);
//Test2(a);

//public class Demo
//{
//    public int Data = 0;
//}

IServiceCollection _serviceCollection = new ServiceCollection();
_serviceCollection.AddTransient<C1>();
_serviceCollection.AddTransient<B1>();
_serviceCollection.AddTransient<A1>();

IServiceProvider _serviceProvider = _serviceCollection.BuildServiceProvider();

C1? _c1 = null;
using (var scope = _serviceProvider.CreateScope())
{
    _c1 = scope.ServiceProvider.GetRequiredService<C1>();
}
_c1.SayA();
_c1.SayB();

public class A1
{
    private readonly IServiceProvider _serviceProvider;

    public A1(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void Say()
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            B1 b1 = scope.ServiceProvider.GetRequiredService<B1>();
            b1.Say();
        }
    }
}

public class B1
{
    public void Say()
    {
        Console.WriteLine(nameof(B1));
    }
}

public class C1
{
    private readonly IServiceProvider _serviceProvider;
    private readonly A1 _a1;

    public C1(IServiceProvider serviceProvider, A1 a1)
    {
        _serviceProvider = serviceProvider;
        _a1 = a1;
    }

    public void SayB()
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            B1 b1 = scope.ServiceProvider.GetRequiredService<B1>();
            b1.Say();
        }
    }

    public void SayA()
    {
        _a1.Say();
    }
}